import { getDefaultOptions } from '~/config'

function setIcon(enable: boolean) {
  chrome.action.setIcon({ path: enable ? 'icons/favicon-32.png' : 'icons/favicon-32-off.png' })
}

async function getActivedTab() {
  const tabs = await chrome.tabs.query({ active: true, windowType: 'normal' })
  return tabs[0]
}

async function updateIcon() {
  const items = await chrome.storage.sync.get()
  const options = Object.assign(getDefaultOptions(), items)
  const activedTab = await getActivedTab()
  const p = new URL(activedTab.url!)
  setIcon(options.globalEnable && !options.domainBlockList.includes(p.hostname))
}

async function sendMessageToContent() {
  const items = await chrome.storage.sync.get()
  const tabs = await chrome.tabs.query({})
  tabs.forEach(tab => {
    chrome.tabs.sendMessage(tab.id!, { type: 'config', data: Object.assign(getDefaultOptions(), items) })
  })
}

/** 快捷键 全局禁用或启用插件 */
async function toggleGlobal() {
  const items = await chrome.storage.sync.get()
  await chrome.storage.sync.set({ globalEnable: items.globalEnable === undefined ? false : !items.globalEnable })
  await sendMessageToContent()
}

/** 快捷键 全局关闭或启用透明度 */
async function toggleOpacity() {
  const items = await chrome.storage.sync.get() as TDefaultOptions
  await chrome.storage.sync.set({ opacity: items.opacity === 100 ? 90 : 100 })
  await sendMessageToContent()
}

chrome.webNavigation.onDOMContentLoaded.addListener(async (details) => {
  if (details.frameId === 0) {

    const store = await chrome.storage.sync.get()

    // 将配置发送到 page.ts 中(即 content_scripts)，由 chrome.runtime.onMessage.addListener 接收
    const activedTab = await getActivedTab();
    chrome.tabs.sendMessage(activedTab.id!, {
      type: 'config',
      data: Object.assign(getDefaultOptions(), store)
    });

    // chrome.scripting.executeScript({
    //   target: {
    //     tabId: details.tabId,
    //   },
    //   func: (d) => {
    //     chrome.runtime.sendMessage(d)
    //       ; (top as any).__CUTTLEFISH_CONFIG__ = d
    //   },
    //   args: [store] // 该数组对应 `func` 函数的 `arguments`。即 `['a', 'b', 'c']` -> `() => console.log(arguments)`
    // })
  }
})

chrome.tabs.onActivated.addListener(activeInfo => {
  updateIcon()
})

chrome.storage.onChanged.addListener((changes, areaName) => {
  if (changes.hasOwnProperty('globalEnable') || changes.hasOwnProperty('domainBlockList')) {
    updateIcon()
  }
})

// chrome.runtime.onMessage.addListener((message, sender, sendRes) => {
//   if (typeof message === 'object') {
//     switch (message.type) {
//       case 'hotkey':
//         chrome.action.setBadgeBackgroundColor({ color: [46, 153, 126, 230] });
//         chrome.action.setBadgeText({ text: message.data ? 'E' : 'F' });
//         break
//     }
//   }
// })

updateIcon().then()

/** 监听快捷键 */
chrome.commands.onCommand.addListener(async (cmd, tab) => {
  switch (cmd) {
    case 'switch-page':
      chrome.tabs.sendMessage(tab.id!, { type: cmd })
      break
    case 'toggle-mask':
      chrome.tabs.sendMessage(tab.id!, { type: cmd })
      break
    case 'toggle-global':
      toggleGlobal()
      break
    case 'toggle-opacity':
      toggleOpacity()
      break
    default:
  }
})
